<!--
 * @Author: wangming
 * @Date: 2021-04-21 10:40:46
 * @LastEditors: wangming
 * @LastEditTime: 2022-04-21 11:13:31
 * @Description: file content
-->
<template>
  <el-input
    v-if="isEdit"
    :style="{
      width: config.__config.width + '%',
    }"
    :placeholder="config.__config.placeholder"
  />
  <div
    v-else-if="!viewInfo"
    :style="{ width: config.__config.width + '%', display: 'inline-block' }"
  >
    <el-select
      clearable
      @click.native="showModel"
      :disabled="disabled"
      :value="selectValue"
      :multiple="config.__config.multiple"
      :placeholder="config.__config.placeholder"
      :style="{ width: '100%' }"
      filterable
      value-key="value"
      @change="change"
      :popper-class="config.__config.treeWalker ? 'dn' : ''"
    >
      <el-option
        v-for="item in optionsList"
        :key="item.value"
        :label="item.label"
        :value="item.value + ''"
      >
      </el-option>
    </el-select>

    <select-modal
      :itemRadio="!config.__config.multiple"
      title="选择人员"
      ref="SelectUserModal"
      :treeData="orgTree"
      :treeNodeChange="handleSelectUserNodeChange"
      @ok="handleUserChange"
    >
    </select-modal>
  </div>
  <div
    v-else
    :style="{
      display: 'inline-block',
      whiteSpace: 'break-spaces',
      width: config.__config.width + '%',
    }"
  >
    <template v-if="config.__config.multiple">
      <el-tag
        style="margin-right: 5px"
        v-for="(item, index) in getViewUser"
        :key="index"
        type="info"
        >{{ item }}
      </el-tag>
    </template>
    <span v-else-if="getViewUser.length > 0">{{ getViewUser[0] }}</span>
  </div>
</template>

<script>
import myMixin from "@/pageComponents/myMixin";
import vmMixin from "@/pageComponents/vmMixin";
import { getHmuserPageListwithpermission } from "@/apis/paas/HmUserController.js";
import { getHmorgListwithpermission } from "@/apis/paas/HmOrgController.js";
import { arrayToTree } from "@/utils/util";
import SelectModal from "@/components/SelectModal";
import storeform from "@/store";
export default {
  name: "Person",
  inject: {
    modelCode: {
      default: null,
    },
  },
  vmEvents: {
    getSelectData() {
      return this.optionsList.filter((i) => {
        if (this.config.__config.multiple) {
          return this.selectValue.indexOf(i.value) > -1;
        } else {
          return i.value == this.selectValue;
        }
      });
    },
  },
  async mounted() {
    if (
      this.config.__config.defaultSelf &&
      this.value === undefined &&
      process.env.VUE_APP_USER !== "ADMIN"
    ) {
      const { id } = this.getUserVal;
      !!id && this.$emit("input", `[${id}]`);
    }
    await this.getInfoList();
    this.changeChildForm();
  },
  components: {
    SelectModal,
  },
  watch: {
    value: {
      handler: "changeChildForm",
    },
    deptIds(val) {
      if (this.deptSelected) {
        this.$emit("input", null);
        if (val === "") {
          this.optionsList = [];
        }
      }
    },
  },
  mixins: [myMixin, vmMixin],
  computed: {
    getUserVal() {
      return storeform.getters.getUserVal;
    },
    selectValue() {
      let value;
      if (this.value) {
        value = (this.value + "").match(/[\w\u4e00-\u9fa5-]+/g);
      }
      if (this.config.__config.multiple) {
        return value || [];
      } else {
        return value ? value[0] : "";
      }
    },
    getViewUser() {
      const viewDatas = [];
      let dataList = [];
      if (this.config.__config.multiple) {
        dataList = this.selectValue || [];
      } else {
        dataList = [this.selectValue];
      }
      dataList.forEach((item) => {
        this.optionsList.forEach((option) => {
          if (option.value === item) {
            viewDatas.push(option.label);
          }
        });
      });
      return viewDatas;
    },
    deptRange() {
      return this.config.__config.deptRange;
    },
    deptSelected() {
      return this.config.__config.deptSelected;
    },
    deptIds() {
      let ids = "";
      if (this.deptRange && this.deptSelected && this.form[this.deptSelected]) {
        try {
          ids = this.form[this.deptSelected]
            .match(/\[(\w+)\]/g)
            .map((item) => item.replace(/[[\]]/g, ""))
            .join(",");
        } catch (error) {}
      }
      return ids;
    },
  },
  methods: {
    changeChildForm() {
      if (!!this.descForm) {
        let desc = "";
        try {
          if (this.config.__config.multiple) {
            desc =
              this.optionsList
                .filter((i) => {
                  return this.selectValue.indexOf(i.value) > -1;
                })
                .map((i) => i.label) + "";
          } else {
            desc = this.optionsList.find((i) => this.selectValue === i.value)
              .label;
          }
        } catch (error) {}
        this.descForm[this.config.modelName] = desc;
      }
    },
    async showModel() {
      if (this.disabled || this.isEdit) {
        return;
      }
      if (this.deptRange) {
        this.getInfoList();
      }
      if (this.config.__config.treeWalker) {
        const data = await getHmorgListwithpermission({
          useCache: true,
        });
        this.orgTree = arrayToTree(data);
        this.$refs.SelectUserModal.open(this.selectValue);
      }
    },

    handleUserChange(data) {
      const { item } = data;
      this.change(item.map((i) => i.id));
    },

    handleSelectUserNodeChange(org) {
      return getHmuserPageListwithpermission({
        pageSize: 100000,
        pageNo: 1,
        orgIds: org.id,
        status: 1,
        modelCode: this.modelCode,
        columnCode: this.config.modelName,
      }).then((res) => {
        return res.data.map((item) => ({
          ...item,
          name: item?.nodeDisplayValue || item.name,
          id: String(item.id),
        }));
      });
    },

    async getInfoList({ keyword = "", pageNo = 1, pageSize = 10000 } = {}) {
      if (
        (this.deptRange && !this.deptSelected) ||
        (this.deptRange && this.deptSelected && this.deptIds === "")
      )
        return [];

      const { data } = await getHmuserPageListwithpermission(
        {
          name: keyword,
          pageNo,
          pageSize,
          orgIds: this.deptIds,
          status: 1,
          modelCode: this.modelCode,
          columnCode: this.config.modelName,
        },
        { useCache: true }
      );
      this.optionsList = data.map((i) =>
        Object.assign({
          label: i?.nodeDisplayValue,
          value: i.id + "",
        })
      );
    },
    async change(v) {
      if (this.config.__config.multiple) {
        this.$emit("input", (v || []).map((item) => `[${item}]`).join(""));
      } else {
        this.$emit("input", v ? `[${v}]` : "");
      }
      this.runEventName("change");
    },
  },
  data() {
    return {
      optionsList: [],
      orgTree: [],
    };
  },
};
</script>

<style lang="scss" scoped></style>
